package com.sixks.app.mvc.cmd;

import com.alibaba.fastjson.JSON;
import com.sixks.app.AliExpressConstant;
import com.sixks.app.api.ApiCallService;
import com.sixks.app.domain.ExpressUser;
import com.sixks.app.mvc.cmd.exception.ExpressAPIException;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author colin
 *         上传图片
 * @date: 02/03/2014
 * @time: 11:19
 */
public class UploadPic extends BaseCommandAPI<UploadPicRequest> {

    @Override
    protected APIResponse handle(UploadPicRequest request, ExpressUser user) throws ExpressAPIException {
        //从requet.getUrlOfImage()上下载图片/
        //是否需要对图片进行处理（大小）
        byte[] image = new byte[0];
        ImageHandler imageHandler = new DefaultHandler();
        image = imageHandler.handle(request);

        Map<String, String> params = new HashMap<String, String>();

        params.put("fileName", request.getImageName());
        params.put("access_token", user.getAccessToken());

        String json;
        try {
            json = ApiCallService.callUploadImage2Bank(params, image);
        } catch (ExpressAPIException e) {
            throw new ExpressAPIException(e.getCode(), e.getMessage());
        }
        Map<String, String> result = JSON.parseObject(json, Map.class);

        APIResponse s = new APIResponse();
        s.setMessage(result.get("photobankUrl"));
        return s;
    }

    interface ImageHandler {
        byte[] handle(UploadPicRequest request);

        byte[] handle(File image);
    }

    class DefaultHandler implements ImageHandler {

        @Override
        public byte[] handle(UploadPicRequest request) {
            return handle(downloadToLocal(request));
        }

        @Override
        public byte[] handle(File image) {

            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            try {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(image));
//                System.out.println("Available bytes:" + in.available());
                byte[] temp = new byte[1024];
                int size;
                while ((size = in.read(temp)) != -1) {
                    out.write(temp, 0, size);
                }
                in.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return out.toByteArray();
        }

        private File downloadToLocal(UploadPicRequest request) {
            //先下载，再保存到具体位置
            String name ="bankImage_"+RandomStringUtils.randomAlphabetic(4)+"_"+request.getImageName();
            String scaleName = "scale_"+name;
            String directory = System.getProperty("user.dir")+File.separator;
            String fileName = directory + name;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(fileName);
                fos.write(ImageReaderUtil.getBytesByURL(request.getUrlOfImage()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fos != null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //
            try {
                Thumbnails.of(new File(fileName))
                        .size(160, 160)
                        .toFile(new File(directory + scaleName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new File(directory+scaleName);
        }
    }
}
